import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps, ProFormInstance } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
  ProForm,
  ProFormDigit,
} from '@ant-design/pro-components';
import { Button, Drawer, message, Popconfirm, PopconfirmProps, Switch } from 'antd';
import React, { useRef, useState, useEffect, act } from 'react';
import type { FormValueType } from './components/UpdateForm';
import type { TableListItem, TableListPagination } from './data';
import { addRule, removeRule, rule, updateRule } from './service';
import ImageUpload from '@/components/ImageUpload';


/**
 * 删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule({
      id: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const [uploadUrl, setUploadUrl] = useState<string>('');
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [isEditing, setIsEditing] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  const [activeKey, setActiveKey] = useState<string>('1');
  const formRef = useRef<ProFormInstance>();
  
const confirm: PopconfirmProps['onConfirm'] = async (e) => {
  const id = e;
  await removeRule({ id: id });
  message.success('删除成功');
  actionRef.current?.reloadAndRest?.();
};
  const handleAdd = async (fields: TableListItem) => {
    const hide = message.loading('正在添加');
    try {
      await addRule({ ...fields, url: uploadUrl ,position:activeKey});
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };
  
  async function handleToggleEnable(id: any, enabled: boolean): Promise<void> {
    try {
      await updateRule({ id,  status: enabled ? 1 : 0 });
      actionRef.current?.reloadAndRest?.();
      message.success(enabled ? '启用成功' : '禁用成功');
    } catch (error) {
      message.error(enabled ? '启用失败' : '禁用失败');
    }
  }

  /**
   * 更新节点
   */
  const handleUpdate = async (fields: FormValueType, currentRow?: TableListItem) => {
    const hide = message.loading('正在保存');
    try {
      await updateRule({
        ...currentRow,
        ...fields,
        url: uploadUrl,
      });
      hide();
      message.success('保存成功');
      return true;
    } catch (error) {
      hide();
      message.error('保存失败请重试');
      return false;
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '图片',
      dataIndex: 'url',
      render: (text) => <img src={text} alt="图片" style={{ width: 100, height: 50 }} />,
    },
    {
      title: '轮播图名称',
      dataIndex: 'name',
      ellipsis: true,
      render: (dom, entity) => (
        <a
          onClick={async () => {
            setCurrentRow(entity);
            setIsEditing(true);
            setDrawerVisible(true);
            setUploadUrl(entity.url); // Set the initial upload URL
          }}
        >
          {dom}
        </a>
      ),
    },
    {
      title: '描述',
      dataIndex: 'subtitle',
      valueType: 'textarea',
      ellipsis: true
    },
    {
      width:120,
      title: '跳转链接',
      dataIndex: 'target',
      hideInForm: true,
      renderText: (val: string) => `${val||''}`,
      ellipsis:true
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'date',
    },
    {
      title: '启用/禁用',
      dataIndex: 'status',
      render: (text, record) => (
        <Switch
          checked={record.status === 1}
          onChange={(checked) => handleToggleEnable(record.id, checked)}
        />
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setCurrentRow(record);
            setIsEditing(true);
            setDrawerVisible(true);
            setUploadUrl(record.url); // Set the initial upload URL
          }}
        >
          编辑
        </a>,
        // <a key="subscribeAlert">上架</a>,
        ( activeKey !== '2' && activeKey !== '3') && <Popconfirm
          key="delete"
          title="确定删除吗？"
          onConfirm={() => confirm(record.id)}
        >
        <a key="subscribeAlert"> 删除 </a>
        </Popconfirm>
        
      ],
    },
  ];

    const imageUploadPropsMap = {
      '1': { maxWidth: 1920, maxHeight: 510 },
      '2': { maxWidth: 1200, maxHeight: 400 },
      '3': { maxWidth: 1024, maxHeight: 300 },
      '4': { maxWidth: 1920, maxHeight: 98 },
      '5': { maxWidth: 1920, maxHeight: 450 },
      '7': { maxWidth: 1920, maxHeight: 450 },
      '8': { maxWidth: 1920, maxHeight: 450 },
    };
  
    const getImageUploadProps = (activeKey: string) => {
      return imageUploadPropsMap[activeKey] || {};
    };

  
  useEffect(() => {
    if (drawerVisible && formRef.current) {
      formRef.current.setFieldsValue(currentRow || {});
    }
  }, [drawerVisible, currentRow]);

  return (
    <PageContainer  header={{
      title: '', 
    }}>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setIsEditing(false);
              setCurrentRow(undefined);
              setDrawerVisible(true);
              setUploadUrl(''); // Reset the upload URL
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        
        
        toolbar={{
          menu: {
              type: 'tab',
              activeKey: activeKey,
              items: [
                  {
                      key: '1',
                      label: <span>首页</span>,
                  },
                  {
                      key: '2',
                      label: <span>解决方案</span>,
                  },
                  {
                      key: '3',
                      label: <span>产品</span>,
                  },
                  {
                      key: '4',
                      label: <span>API</span>,
                  },
                  {
                      key: '5',
                      label: <span>关于我们</span>,
                  }, 
                //   {
                //     key: '6',
                //     label: <span>支持与帮助</span>,
                // },
                  {
                    key: '7',
                    label: <span>新闻中心</span>,
                },
                {
                  key: '8',
                  label: <span>协议Banner</span>,
              },
              {
                key: '9',
                label: <span>行业资讯</span>,
            },
                 
              ],
              onChange: (key) => {
                  setActiveKey(key as string);
                  actionRef.current?.reloadAndRest();
              },
          },
          actions: [
           ( activeKey !== '2' && activeKey !== '3' ) &&
              <Button
                  key="create"
                  type="primary"
                  onClick={() => {
                    
                    setIsEditing(false);
                    setCurrentRow(undefined);
                    setDrawerVisible(true);
                    setUploadUrl(''); // Reset the upload URL
                    
                  }}
              >
                  新建
              </Button>,
          ]
      }}
        
        request={(params) => rule({ ...params,  position: activeKey })}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <Drawer
        title={isEditing ? "编辑" : "新建"}
        width={600}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        destroyOnClose
      >
        <ProForm
          layout="vertical"
          formRef={formRef}
          initialValues={currentRow || {}}
          onFinish={async (value) => {
            let success = false;
            if (isEditing) {
              success = await handleUpdate(value, currentRow);
            } else {
              success = await handleAdd(value as TableListItem);
            }

            if (success) {
              setDrawerVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormText
           label="轮播图名称"
            rules={[
              {
                required: true,
                message: '名称为必填项',
              }
            ]}
            name="name"
          />
          <ProFormTextArea  label="描述" name="subtitle" />
          <ProForm.Item
            name="url"
            label="图片"
            rules={[{ required: true, message: '请上传图片' }]}
          >
            <ImageUpload maxWidth={getImageUploadProps(activeKey).maxWidth} maxHeight={getImageUploadProps(activeKey).maxHeight} value={uploadUrl} onChange={(url) => setUploadUrl(url)} />
          </ProForm.Item>
          <ProFormText label="图片alt" name="alt"></ProFormText>
          <ProFormText
           label="跳转链接"
            name="target"
          />
          <ProFormDigit name="sort" label="排序" />
        </ProForm>
        
      </Drawer>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
